package com.xinkao.example.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xinkao.example.dao.DictValueDao;
import com.xinkao.example.dao.LoginDao;
import com.xinkao.example.dao.MenuDao;
import com.xinkao.example.service.CommonService;
import com.xinkao.example.util.CommonUtil;
import com.xinkao.example.util.model.MenuModel;
import com.xinkao.example.util.model.MenuTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
 * @author zhoujing
 * @date 2021/3/11 9:15
 * @description 公共类
 */
@Service
public class CommonServiceImpl implements CommonService {


    @Resource
    private DictValueDao dictValueDao;

    @Resource
    private MenuDao menuDao;


    @Override
    public List<MenuModel> getMenuTree(String parentId) {
//        List<MenuModel> modelList = menuDao.getMenuTree(parentId);
//        for(MenuModel model : modelList){
//            model.setChildren(getMenuTree(model.getMenuId()));
//        }

        List<MenuModel> modelList = new ArrayList<>();
        List<MenuModel> menuList = menuDao.getAllMenu();
        for(MenuModel menu : menuList){
            if(StrUtil.isEmpty(menu.getParentId())){
                modelList.add(menu);
            }
        }
        if(CollUtil.isNotEmpty(modelList)){
            getTree(modelList, menuList);
        }
        return modelList;
    }

    /**
     * 递归处理树形数据
     * @Author lililiang
     * @Date 2021/8/24 17:43
     */
    private void getTree(List<MenuModel> parentList, List<MenuModel> allList) {
        for(MenuModel p : parentList){
            for(MenuModel menu : allList){
                if(p.getMenuId().equals(menu.getParentId())){
                    p.getChildren().add(menu);
                }
            }
            if(CollUtil.isNotEmpty(p.getChildren())){
                getTree(p.getChildren(), allList);
            }
        }
    }

    /**
     * 查字典
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject getDictList(JSONObject jsonObject){
        List<JSONObject> list = dictValueDao.getDictValueByKey(jsonObject);
        return CommonUtil.successJson(list);
    }
}
